﻿using DreamCMS.BLL.Factory.Interface;
using DreamCMS.Entity;
using DreamCMS.Entity.Common;
using DreamCMS.WebCore.Common;
using DreamCMS.WebCore.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DreamCMS.DAL.DataAccessObject
{
    public class CategoryDAO : ICategoryDAO
    {
        #region Get
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public List<CategoryInfo> GetAllCategory()
        {
            string condition = " [termtype]=" + (long)CatType.MainCat;

            string cmdText = "select * from [dm_Terms] where " + condition + "  order by [displayorder] asc,[termid] asc";

            return DataSetToList(AccessHelper.ExecuteDataSet(CommandType.Text, cmdText));
        }
        #endregion

        #region Update
        /// <summary>
        /// 更新类别
        /// </summary>
        /// <param name="cat">类别实体</param>
        /// <returns>受影响行数</returns>
        public long UpdateCategory(CategoryInfo cat)
        {
            this.ProcessSlug(cat);

            string cmdText = @"update [dm_Terms] set
                                [termtype]=@Type,
                                [name]=@Name,
                                [slug]=@Slug,
                                [description]=@Description,
                                [displayorder]=@Displayorder,
                                [postcount]=@Count,
                                [createdate]=@CreateDate
                                where termid=@termid";
            OleDbParameter[] prams = { 
                                AccessHelper.MakeParam("@Type",OleDbType.Integer,1,ParameterDirection.Input,(long)CatType.MainCat),
								AccessHelper.MakeParam("@Name",OleDbType.VarWChar,255,ParameterDirection.Input,cat.Name),
                                AccessHelper.MakeParam("@Slug",OleDbType.VarWChar,255,ParameterDirection.Input,cat.Slug),
								AccessHelper.MakeParam("@Description",OleDbType.VarWChar,255,ParameterDirection.Input,cat.Description),
                                AccessHelper.MakeParam("@Displayorder",OleDbType.Integer,8,ParameterDirection.Input,cat.Diplayorder),
								AccessHelper.MakeParam("@Count",OleDbType.Integer,8,ParameterDirection.Input,cat.PostCount),
								AccessHelper.MakeParam("@CreateDate",OleDbType.Date,8,ParameterDirection.Input,cat.CreateDate),
                                AccessHelper.MakeParam("@termid",OleDbType.Integer,1,ParameterDirection.Input,cat.CatId),
							};
            return Convert.ToInt64(AccessHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams));
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除类别
        /// </summary>
        /// <param name="catId">类别ID</param>
        /// <returns>受影响行数</returns>
        public long DeleteCategory(long catId)
        {
            string cmdText = "delete from [dm_Terms] where [termid] = @termid";
            OleDbParameter[] prams = { 
								AccessHelper.MakeParam("@termid",OleDbType.Integer,8,ParameterDirection.Input,catId)
							};
            return AccessHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams);
        }
        #endregion

        #region Insert
        /// <summary>
        /// 插入一个类别
        /// </summary>
        /// <param name="cat">类别实体</param>
        /// <returns>返回刚刚插入的类别ID</returns>
        public long AddCategory(CategoryInfo cat)
        {
            this.ProcessSlug(cat);

            string cmdText = @"insert into [dm_Terms]
                            (
                            [termtype],[name],[slug],[description],[displayorder],[postcount],[createdate]
                            )
                            values
                            (
                            @Type,@Name,@Slug,@Description,@Displayorder,@Count,@CreateDate
                            )";
            OleDbParameter[] prams = { 
                                AccessHelper.MakeParam("@Type",OleDbType.Integer,1,ParameterDirection.Input,(long)CatType.MainCat),
								AccessHelper.MakeParam("@Name",OleDbType.VarWChar,255,ParameterDirection.Input,cat.Name),
                                AccessHelper.MakeParam("@Slug",OleDbType.VarWChar,255,ParameterDirection.Input,cat.Slug),
								AccessHelper.MakeParam("@Description",OleDbType.VarWChar,255,ParameterDirection.Input,cat.Description),
                                AccessHelper.MakeParam("@Displayorder",OleDbType.Integer,8,ParameterDirection.Input,cat.Diplayorder),
								AccessHelper.MakeParam("@Count",OleDbType.Integer,8,ParameterDirection.Input,cat.PostCount),
								AccessHelper.MakeParam("@CreateDate",OleDbType.Date,8,ParameterDirection.Input,cat.CreateDate)
							};
            AccessHelper.ExecuteScalar(CommandType.Text, cmdText, prams);

            long newId = Convert.ToInt64(AccessHelper.ExecuteScalar(CommandType.Text, "select top 1 [termid] from [dm_Terms] order by [termid] desc"));

            return newId;
        }
        #endregion

        #region Others
        /// <summary>
        /// 检查别名是否重复
        /// </summary>
        /// <param name="term"></param>
        /// <returns></returns>
        private void ProcessSlug(CategoryInfo cat)
        {
            if (string.IsNullOrEmpty(cat.Slug))
            {
                return;  //若别名为空，则表示没有重复。则往数据库中插入空数据。自然列表页页显示时就使用ID来显示。
            }
            int i = 0;
            while (i < 2)
            {
                string cmdText = string.Empty;
                if (cat.CatId == 0)  //插入新类别的时候，类别ID是没有的，但插入类别也需要判断slug是否重复
                {
                    cmdText = string.Format("select count(1) from [dm_Terms] where [slug]='{0}'  ", cat.Slug);
                }
                else
                {
                    //更新文章就要看除了当前文章以外的文章有没有重复Slug
                    cmdText = string.Format("select count(1) from [dm_Posts] where [slug]='{0}'   and [postid]<>{1}", cat.Slug, cat.CatId);
                }
                long r = Convert.ToInt64(AccessHelper.ExecuteScalar(CommandType.Text, cmdText)); //得到结果行数
                if (r == 0) //表明没有重复行，1表示已经查询到了slug在数据库中有相应的记录
                {
                    return;  //没有重复，则退出
                }
                else if (r != 0 && i == 0)
                {
                    cat.Slug += VerifyCodeHelper.GetCode(3); //如果重复，则自动更改slug. 如果第二次循环还是重复，则置空
                    i++;
                }
                else
                {
                    i++;
                }
            }
        }

        private List<CategoryInfo> DataSetToList(DataSet ds)
        {
            List<CategoryInfo> list = new List<CategoryInfo>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                CategoryInfo cat = new CategoryInfo();
                cat.CatId = StringHelper.ObjectToInt64(dr["termid"], 0);
                cat.CreateDate = Convert.ToDateTime(dr["createdate"]);
                cat.Description = Convert.ToString(dr["description"]);
                cat.Diplayorder = StringHelper.ObjectToInt64(dr["displayorder"], 0);
                cat.Name = Convert.ToString(dr["name"]);
                cat.PostCount = StringHelper.ObjectToInt64(dr["postcount"], 0);
                cat.Slug = Convert.ToString(dr["slug"]);
                cat.Type = (CatType)(StringHelper.ObjectToInt64(dr["termtype"], 0));
                list.Add(cat);
            }
            return list;
        }
        #endregion

    }
}
